# -*- coding: utf-8 -*-
from PyQt5.Qt import QThread
from PyQt5.QtCore import (Qt, QObject, QTime, pyqtSlot, pyqtSignal)
from PyQt5.QtWidgets import (QLabel, QLineEdit, QTextEdit, QTimeEdit, QSpinBox, QCheckBox, QPushButton, QHBoxLayout, QVBoxLayout, QWidget, QApplication, QMainWindow, QMessageBox)
from datetime import datetime
import win32con
import win32gui
import win32api
import time
import socket
import base64
import json
import requests
import configparser
import os

class ThreadAgent(QThread):
    _signal = pyqtSignal(str, str)

    def __init__(self, sec_diff, end_time, today, jjia, tper):
        super().__init__()
        self.sec_diff = sec_diff
        self.end_time = end_time
        self.today = today
        self.jjia  = jjia
        self.tper  = tper
        self._cmd  = ''
        self.tfrm  = win32gui.FindWindow("Tfrm_Main", None)

    def run(self):
        tm1 = '%s %s' % (self.today, self.end_time)
        while True:
            tm2 = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + float(self.sec_diff)))
            hm2 = str(time.time())[11:12]

            hm2set = [
                ['1'],
                ['5'],
                ['4', '9'],
                ['3', '6', '9'],
                ['1', '4', '7', '9'],
                ['0', '2', '4', '6', '8'],
                ['1', '3', '5', '7', '9', '0'],
                ['1', '2', '4', '5', '6', '8', '9'],
                ['1', '2', '4', '5', '6', '8', '9', '0'],
                ['1', '2', '3', '4', '5', '6', '8', '9', '0'],
                ['1', '2', '3', '4', '5', '7', '6', '8', '9', '0']
            ]

            if hm2 in hm2set[self.tper]:
                if self.jjia is 'yes':
                    self.f5()
                self.f9()
            self._signal.emit('run', '运行代理 > %s.%s0' % (tm2, hm2))
            
            if self.diff_seconds(tm1, tm2) < 0:
                self._signal.emit('stop', '竞价结束 < %s' % tm2)
                break
            if self._cmd is 'stop':
                self._signal.emit('stop', '已停止代理')
                break

            time.sleep(0.1)

    def send(self, cmd):
        self._cmd = cmd

    def f5(self):
        win32api.PostMessage(self.tfrm, win32con.WM_KEYDOWN, win32con.VK_F5, 0)
        win32api.PostMessage(self.tfrm, win32con.WM_KEYUP, win32con.VK_F5, 0)

    def f9(self):
        win32api.PostMessage(self.tfrm, win32con.WM_KEYDOWN, win32con.VK_F9, 0)
        win32api.PostMessage(self.tfrm, win32con.WM_KEYUP, win32con.VK_F9, 0)

    def diff_seconds(self, tm1, tm2):
        tm1 = datetime.strptime(tm1, '%Y-%m-%d %H:%M:%S')
        tm2 = datetime.strptime(tm2, '%Y-%m-%d %H:%M:%S')
        sec = (tm1 - tm2).seconds
        if sec > 80000:
            sec = -1 * (86400 - sec)
        return sec


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.today  = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        self.setWindowTitle('xmAgent1.0')
        self.createLayouts()
        self.resize(300, 80)
        self.createStatusBar()
        
        self.status = 'stop' 
        self.jjia     = ''    #是否加价
        self.sec_diff = 0     #时间差
        self.end_time = ''    #结束时间
        self.sys_time = ''    #服务器时间
        self.ms_time  = 0

    def btnStart_click(self):
        if self.status is 'stop':
            self.file_diff_seconds()
            self.btnStart.setText('停止')
            self.jjia     = 'yes' if self.jiaLabel.isChecked() else ''
            self.end_time = self.tmEdit.time().toString('HH:mm:ss')
            self.tdAgent  = ThreadAgent(self.sec_diff, self.end_time, self.today, self.jjia, self.comboBox.value())
            self.tdAgent._signal.connect(self.theadBack)
            self.tdAgent.start()
            self.status = 'run'
        else:
            self.status = 'stop'
            self.btnStart.setText('开始')
            self.tdAgent.send('stop')
        #self.btnStart.setEnabled(False)

    def theadBack(self, cmd, msg):
        if cmd == 'stop':
            self.btnStart.setText('开始')
            self.statusBar().showMessage(" %s" % msg)
        else:
            self.statusBar().showMessage(" %s" % msg)

    def createStatusBar(self):
        self.ms_time = self.tcp_ms_time()
        self.file_diff_seconds()
        tm = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + float(self.sec_diff)))
        self.statusBar().showMessage(" [同步]系统时间:%s - %sms" % (tm, self.ms_time))

    def createLayouts(self):
        self.jiaLabel = QCheckBox('加价', self)
        self.tmLabel  = QLabel('结束时间')
        self.tmEdit   = QTimeEdit()
        self.tmEdit.setDisplayFormat('HH:mm:ss')
        self.tmEdit.setTime(QTime.currentTime())
        self.comboBox = QSpinBox()
        self.comboBox.setMinimum(2)
        self.comboBox.setMaximum(10)
        self.comboBox.setValue(4)
        self.comLabel = QLabel('次/秒')

        self.btnStart = QPushButton('开始')
        self.btnStart.clicked.connect(self.btnStart_click)

        self.pwdLabel = QLabel('密码')
        self.pwdEdit  = QLineEdit()
        self.jafLabel = QLabel('场次')
        self.jafEdit  = QTextEdit()

        self.mainLayout = QVBoxLayout()
        self.m1Layout = QHBoxLayout()
        self.m1Layout.addWidget(self.jiaLabel)
        self.m1Layout.addWidget(self.tmLabel)
        self.m1Layout.addWidget(self.tmEdit)
        self.m1Layout.addWidget(self.comboBox)
        self.m1Layout.addWidget(self.comLabel)
        self.m1Layout.addWidget(self.btnStart)
        self.mainLayout.addLayout(self.m1Layout)

        '''
        self.m2Layout = QHBoxLayout()
        self.m2Layout.addWidget(self.pwdLabel)
        self.m2Layout.addWidget(self.pwdEdit)
        self.mainLayout.addLayout(self.m2Layout)


        self.m3Layout = QHBoxLayout()
        self.m3Layout.addWidget(self.jafLabel)
        self.m3Layout.addWidget(self.jafEdit)
        self.mainLayout.addLayout(self.m3Layout)
        '''

        self.mainWidget = QWidget()
        self.mainWidget.setLayout(self.mainLayout)
        self.setCentralWidget(self.mainWidget)
        self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)

    def file_diff_seconds(self):
        log_file = 'Logs/%s.log' % self.today
        key_txt  = '[同步]系统时间:'
        sys_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
        win_time = sys_time
        try:
            with open(log_file) as f:
                lines = f.readlines()
                for line in lines:
                    if key_txt in line:
                        fi = line.find(key_txt)
                        sys_time = line[fi+len(key_txt):].strip()
                        win_time = '%s %s' % (self.today, line[fi-9:fi].strip())
        except:
            pass
        self.sys_time = sys_time
        self.sec_diff = self.diff_seconds(sys_time, win_time) - self.ms_time

    def diff_seconds(self, tm1, tm2):
        tm1 = datetime.strptime(tm1, '%Y-%m-%d %H:%M:%S')
        tm2 = datetime.strptime(tm2, '%Y-%m-%d %H:%M:%S')
        sec = (tm1 - tm2).seconds
        if sec > 80000:
            sec = -1 * (86400 - sec)
        return sec

    def tcp_ms_time(self):
        ms_total   = 0
        for i in range(0, 10):
            tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            stime = time.time()
            tcp_socket.connect(('113.200.102.203', 8888))
            etime = time.time()
            ms = int((etime - stime) * 10000)
            ms_total += ms
            tcp_socket.close()
            time.sleep(0.1)
        return float(ms_total / 10)

    def client_token(self):
        config = configparser.ConfigParser()
        config.read('Default.ini')
        account = config.get('User','User')
        verifycode,captcha_token = self.verifycode()
        if 'OK' == verifycode[0:2]:
            verifycode = verifycode[2:]
        else:
            QMessageBox().information(None, '提示', '验证码识别%s' % verifycode , QMessageBox.Yes)
            #return True
        verifycode = '1245'
        data = {"account":account,"pwd":"111111","source":"H5","verifycode":verifycode,"captcha_token":captcha_token}
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        res = requests.post('https://client.westcoal.com.cn/api/mid/v1/MT1100', json=data, headers=headers).json()
        if '000000' == res['result']:
            token = res['data']['token']
        else:
            error = res['msg']
            QMessageBox().information(None, '提示', error, QMessageBox.Yes)

    def verifycode(self):
        res = requests.post('https://client.westcoal.com.cn/api/mid/v1/MT1002', data={}).json()
        captcha_token = res['data']['CAPTCHA_TOKEN']
        imgurl = 'https://client.westcoal.com.cn/api/mid/v1/captcha?value=%s' % captcha_token
        tmp = requests.get(imgurl,stream=True)
        path = 'captcha.png'
        with open(path, 'wb') as fd:
            for chunk in tmp.iter_content():
                fd.write(chunk)
        with open(path, 'rb') as f:
            base64_data = base64.b64encode(f.read())
            b64 = base64_data.decode()
        verifycode = self.base64_api(b64)
        os.remove(path)
        return verifycode,captcha_token

    def base64_api(self, b64):
        uname = ''
        pwd   = ''
        data  = {"username": uname, "password": pwd, "typeid": 1, "image": b64}
        res   = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
        if res['success']:
            return 'OK%s' % res['data']['result']
        else:
            return res['message']
        return ''


if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())
